package com.leyou.system.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.common.domain.PageResult;
import com.leyou.common.exception.domain.ExceptionEnum;
import com.leyou.common.exception.domain.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.system.domain.Role;
import com.leyou.system.domain.User;
import com.leyou.system.dto.SysUserDto;
import com.leyou.system.mapper.RoleMapper;
import com.leyou.system.mapper.UserMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class UserService {

	@Autowired
	private BCryptPasswordEncoder encoder;

	@Autowired
	private UserMapper userMapper;

	@Autowired
	private RoleMapper roleMapper;

	public PageResult<SysUserDto> userPageQuery(Integer page, Integer rows, String key, Boolean status, String sortBy, Boolean desc) {
		PageHelper.startPage(page,rows);
		Example example = new Example(User.class);
		Example.Criteria criteria = example.createCriteria();
		if (!StringUtils.isEmpty(key)) {
			criteria.andLike("name","%"+key+"%");
		}
		if (status != null) {
			criteria.andEqualTo("status",status);
		}
		List<User> userList = userMapper.selectByExample(example);
		if (CollectionUtils.isEmpty(userList)) {
			throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
		}
		PageInfo<User> userPageInfo = new PageInfo<>(userList);
		List<SysUserDto> userDtoList = BeanHelper.copyWithCollection(userPageInfo.getList(), SysUserDto.class);
		PageResult<SysUserDto> pageResult = new PageResult<>(userPageInfo.getTotal(),userPageInfo.getPages(),userDtoList);
		return pageResult;
	}

	public void addUser(SysUserDto sysUserDto) {
		User user = new User();
		user.setId(sysUserDto.getId());
		user.setUsername(sysUserDto.getUsername());
		user.setPassword(encoder.encode(sysUserDto.getPassword()));
		user.setStatus(sysUserDto.getStatus());
		user.setPhone(sysUserDto.getPhone());

		int count = userMapper.insertSelective(user);
		if (count!=1){
			throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
		}

		List<String> roleNames = sysUserDto.getRoles();
		List<Role> roles = roleMapper.selectAll();
		ArrayList<Integer> roleIds = new ArrayList<>();
		for (String roleName : roleNames) {
			for (Role role : roles) {
				if (role.getRoleName().equals(roleName)){
					roleIds.add(role.getId());
				}
			}
		}
		count = userMapper.addUidAndRid(user.getId(),roleIds);
		if (count!=roleIds.size()){
			throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
		}


	}

	public SysUserDto findUserById(String id) {
		User user = userMapper.selectByPrimaryKey(id);
		if (user==null){
			throw new LyException(ExceptionEnum.USER_NOT_FOUND);
		}
		//从中间表查询该用户的角色id
		List<Integer> rids =  userMapper.selectRidAndUid(id);
		ArrayList<String> roles = new ArrayList<>();
		for (Integer rid : rids) {
			Role role = roleMapper.selectByPrimaryKey(rid);
			roles.add(role.getRoleName());
		}
		SysUserDto sysUserDto = BeanHelper.copyProperties(user, SysUserDto.class);
		sysUserDto.setRoles(roles);
		return sysUserDto;
	}


	/*
	修改用户信息
	 */
	public void updateUser(SysUserDto sysUserDto) {
		User user = BeanHelper.copyProperties(sysUserDto, User.class);
		//修改用户信息
		int count = userMapper.updateByPrimaryKeySelective(user);
		if (count!=1){
			throw new LyException(ExceptionEnum.USER_NOT_FOUND);
		}


		//维护中间表
		userMapper.deleteUidAndRid(sysUserDto.getId());

		List<String> roleNames = sysUserDto.getRoles();
		List<Role> roles = roleMapper.selectAll();
		ArrayList<Integer> roleIds = new ArrayList<>();
		for (String roleName : roleNames) {
			for (Role role : roles) {
				if (role.getRoleName().equals(roleName)){
					roleIds.add(role.getId());
				}
			}
		}
		if(!CollectionUtils.isEmpty(roleIds)){
			count = userMapper.addUidAndRid(user.getId(),roleIds);
			if (count!=roleIds.size()){
				throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
			}
		}






	}

	public void deleteUserById(Integer id) {
		//删除中间表
		userMapper.deleteUidAndRid(id);
		userMapper.deleteByPrimaryKey(id);

	}

	/*
	刪除多個用戶
	 */
	public void deleteUserByIds(List<Integer> ids) {

		ids.forEach((id)->{
			deleteUserById(id);
		});
	}
}
